import path from 'path'
import { rollup } from 'rollup'
import commonjs from '@rollup/plugin-commonjs'
import url from '@rollup/plugin-url';
import { nodeResolve } from '@rollup/plugin-node-resolve'
import json from "@rollup/plugin-json";
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDefineOptions from 'unplugin-vue-define-options/rollup'
import esbuild, { minify as minifyPlugin } from 'rollup-plugin-esbuild'
import postcss from 'rollup-plugin-postcss'
import { pkgRoot, outputDist } from '../utils/paths'
import { target, generateExternal } from '../utils/rollup'
import { PKG_CAMELCASE_NAME } from '../utils/constants'
const build = async (minify) => {
  const input = [
    // root
    path.resolve(pkgRoot, 'index.js'),
  ]
  const bundle = await rollup({
    input,
    plugins: [
      vueDefineOptions(),
      vue(),
      vueJsx(),
      url(),
      json(),
      postcss(
        {
          inject: false, // 不直接注入样式到 JS 中，而是提取到单独的文件
          extract: true, // 提取 CSS 到 'bundle-name.css'
        }
      ),
      nodeResolve({ preferBuiltins: false }),
      commonjs(),
      esbuild({
        target,
        sourceMap: minify,
        treeShaking: true,
      }),
      minify
        ? minifyPlugin({
            target,
            sourceMap: minify,
          })
        : null,
    ],
    treeshake: true,
    external: generateExternal({ full: false }),
  })

  await Promise.all([
    bundle.write({
      format: 'esm',
      file: path.resolve(outputDist, `index${minify ? '.min' : ''}.mjs`),
      exports: undefined,
      sourcemap: false,
    }),
    bundle.write({
      format: 'umd',
      file: path.resolve(outputDist, `index${minify ? '.min' : ''}.js`),
      exports: 'named',
      sourcemap: false,
      name: PKG_CAMELCASE_NAME,
      globals: {
        vue: 'Vue',
        vuex: 'vuex',
        'vue-router':'vueRouter',
        'axios':'axios',
        'qs':'qs',
        'element-plus':'elementPlus'
      },
    }),
  ])
}

export const buildFull = async () => {
  await Promise.all([build(false), build(true)])
}
